package com.xs.ahoi.hcxs.ui.fragment;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import butterknife.*;
import com.xs.ahoi.hcxs.R;
import com.xs.ahoi.hcxs.dao.BookDao;
import com.xs.ahoi.hcxs.model.Book;
import com.xs.ahoi.hcxs.service.BookFactory;
import com.xs.ahoi.hcxs.ui.activity.BookBatchActivity;
import com.xs.ahoi.hcxs.ui.activity.BookContentActivity;
import com.xs.ahoi.hcxs.ui.activity.BookImportActivity;
import com.xs.ahoi.hcxs.ui.dialog.DialogBookInfo;
import com.xs.ahoi.hcxs.ui.dialog.DialogShelfMore;
import com.xs.ahoi.hcxs.utils.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * author: ahoi
 * date: 2018/6/27 17:24
 * description: 书架
 */
public class BookShelfFragment extends Fragment {

    @BindView(R.id.lvBookShelf)
    public ListView lvBookShelf;
    @BindView(R.id.layoutMore)
    public RelativeLayout layoutMore;

    private FragmentActivity context;

    private CallbackListener listener;

    List<Map<String, Object>> datas;
    String[] keys = new String[]{"tvBookName", "tvBookInfo", "tvPercent"};
    int[] resources = new int[]{R.id.tvBookName, R.id.tvBookInfo, R.id.tvPercent};
    private BookDao bookDao;
    // 书籍集合
    private List<Book> books;
    // 书籍长按弹框
    private DialogBookInfo dialogBookInfo;
    // 右上角更多弹框
    private DialogShelfMore dialogShelfMore;
    // 小说图标和正在播放的图标
    private Drawable drawableFileIcon, drawablePlaying;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_book_shelf, container, false);
        ButterKnife.bind(this, view);

        context = getActivity();

        // 运行时授权
        String back = context.getIntent().getStringExtra("back");
        if ("1".equals(back)) {
            init();
        } else {
            initPermissions();
        }

        return view;
    }

    public void init() {
        if (context == null) {
            return;
        }

        // 小说图标和正在播放的图标
        drawableFileIcon = ContextCompat.getDrawable(context, R.drawable.icon_file);
        drawablePlaying = ContextCompat.getDrawable(context, R.drawable.icon_music);

        // 初始化弹框
        dialogBookInfo = new DialogBookInfo(this.context);
        dialogBookInfo.setBookInfoListener(new DialogBookInfo.BookInfoListener() {
            @Override
            public void refresh() {
                bindListView();
            }

            @Override
            public void startActivity(Intent intent) {
                BookShelfFragment.this.startActivity(intent);
            }
        });

        // 绑定到listview
        bindListView();

        // 初始化右上角更多弹框
        dialogShelfMore = new DialogShelfMore(this.context);
        dialogShelfMore.setDialogListener(new DialogShelfMore.DialogListener() {
            @Override
            public void importLocal() {
                // 跳转到导入页面
                startActivity(new Intent(BookShelfFragment.this.context, BookImportActivity.class));
            }

            @Override
            public void batchManage() {
                // 跳转到批量管理页面
                startActivity(new Intent(BookShelfFragment.this.context, BookBatchActivity.class));
            }
        });

    }

    // 绑定到listview
    private void bindListView() {
        if (context == null) {
            return;
        }
        bookDao = BookDao.getInstance();
        books = bookDao.listAll();
        datas = books.stream().map(o -> MapUtil.build()
                .put("id", o.getId())
                .put("tvBookName", o.getName())
                .put("tvBookInfo", o.getSize())
                .put("tvPercent", o.getPercent())
                .put("isSettop", o.getSetTopTime())
                .over()).collect(Collectors.toList());

        // listview数据集
        ShelfAdapter adapter = new ShelfAdapter(context, datas, R.layout.listview_item_shelf, keys, resources);
        lvBookShelf.setAdapter(adapter);
    }

    @OnClick({R.id.layoutMore})
    public void onClick(View v) {
        switch (v.getId()) {
            // 右上角更多弹出框
            case R.id.layoutMore:
                dialogShelfMore.setClickedView(layoutMore);
                dialogShelfMore.show();
                break;
            default:
                break;
        }
    }

    @OnItemClick({R.id.lvBookShelf})
    public void onItemClick(int position) {
        // 获取点击的书籍
        Book book = books.get(position);
        book = bookDao.getById(book.getId());

        // 验证书籍路径存不存在
        if (!FileUtil.isFile(book.getPath())) {
            ToastUtil.show(getString(R.string.openFail));
            return;
        }

        // 跳转到内容页面
        Intent intent = new Intent(context, BookContentActivity.class);
        intent.putExtra(Constants.DEFAULT_ID, book.getId());
        startActivity(intent);

        // 设置打开动画
        if (listener != null) {
            listener.back();
        }
    }

    @OnItemLongClick({R.id.lvBookShelf})
    public boolean onItemLongClick(int position) {
        int bookId = books.get(position).getId();
        dialogBookInfo.setBookId(bookId);
        dialogBookInfo.show();
        // 设置进出动画
        dialogBookInfo.getWindow().setWindowAnimations(R.style.dialog_anim);
        return true;
    }

    private class ShelfAdapter extends SimpleAdapter {

        private ShelfAdapter(Context context, List<? extends Map<String, Object>> datas, int resource, String[] from, int[] to) {
            super(context, datas, resource, from, to);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            View view = super.getView(position, convertView, parent);
            Map<String, Object> data = getItem(position);

            // 设置阅读进度
            TextView tvPercent = view.findViewById(R.id.tvPercent);
            tvPercent.setText(ObjectUtils.toString(data.get("tvPercent")));

            // 设置书名
            TextView tvBookName = view.findViewById(R.id.tvBookName);
            tvBookName.setText(ObjectUtils.toString(data.get("tvBookName")));

            // 设置大小和内容
            TextView tvBookInfo = view.findViewById(R.id.tvBookInfo);
            tvBookInfo.setText(ObjectUtils.toString(data.get("tvBookInfo")));

            // 设置置顶
            ImageView ivSetTop = view.findViewById(R.id.ivSetTop);
            long isSettop = ObjectUtils.toLong(data.get("isSettop"));
            ivSetTop.setVisibility(isSettop == 0 ? View.GONE : View.VISIBLE);

            // 设置正在播放的小说图标为播放动画
            ImageView ivFileIcon = view.findViewById(R.id.ivFileIcon);
            int playingBookId = BookFactory.getInstance().getBookId();
            boolean playing = BookFactory.getInstance().isPlaying();
            if (playing && playingBookId != 0 && ObjectUtils.toInteger(data.get("id")) == playingBookId) {
                ivFileIcon.setBackground(drawablePlaying);
            } else {
                ivFileIcon.setBackground(drawableFileIcon);
            }

            return view;
        }

        @Override
        public Map<String, Object> getItem(int position) {
            return datas.get(position);
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            init();
        }
    }

    public void setCallbackListener(CallbackListener listener) {
        this.listener = listener;
    }

    public interface CallbackListener {
        void back();
    }

    private void initPermissions() {
        String[] permissions = {
                Manifest.permission.INTERNET,
                Manifest.permission.ACCESS_NETWORK_STATE,
                Manifest.permission.MODIFY_AUDIO_SETTINGS,
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_SETTINGS,
                Manifest.permission.READ_PHONE_STATE,
                Manifest.permission.ACCESS_WIFI_STATE,
                Manifest.permission.CHANGE_WIFI_STATE
        };

        ArrayList<String> toApplyList = new ArrayList<>();

        for (String perm : permissions) {
            if (PackageManager.PERMISSION_GRANTED != ContextCompat.checkSelfPermission(context, perm)) {
                toApplyList.add(perm);
            }
        }
        String[] tmpList = new String[toApplyList.size()];
        if (toApplyList.size() > 0) {
            ActivityCompat.requestPermissions(context, toApplyList.toArray(tmpList), 124);
        } else {
            init();
        }
    }

    // 授权回调
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        init();
    }


}
